import moment from '@/plugins/moment.js'

/**
 *
 * @param {Date | String} appointDay
 * @returns 返回指定日期当前月的日历数组
 */
export const getCalendar = (appointDay) => {
  // 日历数组
  const calendar = []
  // 需要返回的月日历的某天
  const current = moment(appointDay)
  // 当前月的第一天
  const firstDayOfMonth = moment(current.format('YYYY-MM-01'))
  // 当前月最后一天
  const lastDayOfMonth = current.clone().endOf('month')
  // 统一对日期对象进行处理
  const handleDayFun = (dayIns) => ({
    dayStr: dayIns.format('YYYY-MM-DD'),
    year: dayIns.format('YYYY'),
    month: dayIns.format('M'),
    day: dayIns.format('D'),
    weekOfDay: dayIns.day(),
    moment: dayIns,
    isCurrentMonth: dayIns.format('M') == current.format('M')
  })

  // 星期天在第一格则当月一号为5，则需要再补五天，为0，则需要再补五天

  // 当前月历补充前缀日
  const preDayArr = []
  let preday = firstDayOfMonth.day()
  if (preday == 0) preday = 7
  for (let index = 1; index <= preday - 1; index++) {
    const handleDay = firstDayOfMonth.clone().subtract(index, 'days')
    preDayArr.unshift(handleDayFun(handleDay))
  }
  calendar.push(...preDayArr)

  // 循环填充至这个月最后一天
  const whileDay = firstDayOfMonth.clone()
  while (whileDay <= lastDayOfMonth) {
    calendar.push(handleDayFun(whileDay))
    whileDay.add(1, 'days')
  }

  // 当前月历补充后缀日
  const suffixDayArr = []
  let suffixday = lastDayOfMonth.day()
  if (suffixday == 0) suffixday = 7
  for (let index = 1; index <= 7 - suffixday; index++) {
    suffixDayArr.push(handleDayFun(lastDayOfMonth.clone().add(index, 'days')))
  }
  calendar.push(...suffixDayArr)

  // 补充六行日历模式
  const lastMoment = moment(calendar.at(-1).dayStr)
  const sixRowArr = []
  for (let index = 1; index <= 6 * 7 - calendar.length; index++) {
    sixRowArr.push(handleDayFun(lastMoment.clone().add(index, 'days')))
  }
  calendar.push(...sixRowArr)

  return calendar
}

/**
 * 提取富文本文字内容
 */
export const extractText = (str) => {
  if (!str) return ''
  const parser = new DOMParser()
  const doc = parser.parseFromString(str, 'text/html')
  const textNodes = doc.body.innerText.trim().split('\n').join('')
  return textNodes
}

/**
 * 获取数据的图片
 */
export const getImageUrl = (picItem) => {
  const defaultImage = '/images/course_default.png'
  if (!picItem) return defaultImage
  const jsonObj = JSON.parse(picItem)
  if (!jsonObj) return defaultImage
  return (
    import.meta.env.VITE_APP_FRONT_HOST +
    '/TpwpStatic' +
    jsonObj?.filePathArray[0]?.CompleteFilePath || defaultImage
  )
}

/**
 * 文件图片预览
 */
export const imgReview = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.addEventListener(
      'load',
      function () {
        resolve(reader.result)
      },
      false
    )

    if (file) reader.readAsDataURL(file)
  })
}

/**
 * 专家头像显示
 */
export const showExpertAvator = (experItem) => {
  const defaultImg = '/images/expert_default.png'
  if (!experItem || !experItem.unitId || !experItem.expertPic) {
    return defaultImg
  }

  let userUpload;
  try {
    userUpload = JSON.parse(experItem.expertPic)
  } catch (error) {
    // 非后传的头像显示方式
    return `${import.meta.env.VITE_APP_FRONT_HOST}/TpwpExpertStatic/${experItem.unitId}/${experItem.expertPic}`
  }

  const picUrl = userUpload?.filePathArray[0]?.CompleteFilePath.replace(/\/UploadFiles/g, '') || ''
  // 后传的头像
  if (userUpload) return `${import.meta.env.VITE_APP_FRONT_HOST}/${picUrl}`

  return defaultImg
}
